import axiosInstance from "../../plugins/axios";
import { ElMessage } from "element-plus";
import { Tenant } from "../../type/Tenant";
import { TenantDTO } from "../../type/Tenant";
import { ApiResponse } from "../../type/result";

export const getTenantInfo = async (pageNum: number, pageSize: number) => {
  const res = await axiosInstance.post(
    `/tenants/page?pageNum=${pageNum}&pageSize=${pageSize}`
  );
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "获取租户信息失败");
    throw new Error(res.data.message || "获取租户信息失败");
  }
};

export const getAllTenantInfo = async () => {
  const res = await axiosInstance.get(`/tenants/all`);
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "获取租户信息失败");
    throw new Error(res.data.message || "获取租户信息失败");
  }
};

export const findById = async (id: string): Promise<Tenant>  => {
  const res = await axiosInstance.post(`/tenants/findById?tenantId=${id}`); 
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "获取租户信息失败");
    throw new Error(res.data.message || "获取租户信息失败");
  }
};

export const searchTenantInfo = async (
  pageNum: number,
  pageSize: number,
  search: any
) => {
  const res = await axiosInstance.post("/tenants/search", {
    pageNum,
    pageSize,
    search,
  });
  if (res.data.code === 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "搜索租户信息失败");
    throw new Error(res.data.message || "搜索租户信息失败");
  }
};

export const fetchContactIds = async () => {   
  const res = await axiosInstance.post('/tenants/contactIds'); 
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "获取联系人信息失败");
    throw new Error(res.data.message || "获取联系人信息失败");
  }
};

export const addTenant = async (tenant: TenantDTO) => {
  const res = await axiosInstance.post("/tenants/add", tenant);
  if (res.data.code === 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "添加租户信息失败");
    throw new Error(res.data.message || "添加租户信息失败");
  }
}

export const deleteTenant = async (tenant: TenantDTO) => {
  const res = await axiosInstance.post("/tenants/delete", tenant);
  if (res.data.code === 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "删除租户信息失败");
    throw new Error(res.data.message || "删除租户信息失败");
  }
};

export const deleteBatch = async (ids: string[]) => {
  const res = await axiosInstance.post("/tenants/deleteBatch", ids);
  if (res.data.code === 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "删除租户信息失败");
    throw new Error(res.data.message || "删除租户信息失败");
  }
  
};


export const updateTenant = async (tenant: TenantDTO) => {
  const res = await axiosInstance.post("/tenants/update", tenant);
  if (res.data.code === 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "更新用户信息失败");
    throw new Error(res.data.message || "更新用户信息失败");
  }
};

export const importTenantInfo = async (formData: FormData) => {
  try {
    const res = await axiosInstance.post("/tenants/import", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    if (res.data.code === 1) {
      return res.data.data; // 返回数据
    } else {
      ElMessage.error(res.data.message || "导入租户信息失败");
      throw new Error(res.data.message || "导入租户信息失败");
    }
  } catch (error) {
    
    throw new Error("导入租户信息失败");
  }
};

export const exportTenantInfo = async () => {
  axiosInstance
    .get("/tenants/export", {
      responseType: "blob", // 重要
    })
    .then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      const contentDisposition = response.headers["content-disposition"];
      let fileName = "下载文件.xlsx";
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(
          /filename\*=UTF-8''(.+)/
        );
        if (fileNameMatch.length === 2) {
          fileName = decodeURIComponent(fileNameMatch[1]);
        }
      }
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
    })
    .catch((error) => {
      ElMessage.error("下载失败，请重试");
      console.error("下载失败:", error);
    });
};